import { Button, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router-dom';

import permissionService from '@/api/services/security/permissionService';
import roleService from '@/api/services/security/roleService';
import Card from '@/components/card';
import { useUserActions } from '@/store/userStore';

type FieldType = {
  password?: string;
  newPassword?: string;
  confirmPassword?: string;
};

// 密码验证规则
const PASSWORD_PATTERN = {
  validator: (_: any, value: string) => {
    if (!value) {
      return Promise.reject(new Error('请输入密码'));
    }

    // 检查长度
    if (value.length < 6 || value.length > 20) {
      return Promise.reject(new Error('密码长度必须在6-20位之间'));
    }

    // 检查各种字符类型
    const patterns = {
      lowercase: /[a-z]/,
      uppercase: /[A-Z]/,
      number: /[0-9]/,
      special: /[!@#$%^&*(),.?":{}|<>]/,
    };

    // 计算匹配的字符类型数量
    const matchCount = Object.values(patterns).reduce(
      (count, pattern) => count + (pattern.test(value) ? 1 : 0),
      0,
    );

    if (matchCount < 3) {
      return Promise.reject(
        new Error('密码必须包含大小写字母、数字和特殊字符(!@#$%^&*(),.?":{}|<>)中的任意三种'),
      );
    }

    return Promise.resolve();
  },
};

export default function SecurityTab() {
  const [form] = Form.useForm();

  const initFormValues = {
    password: '',
    newPassword: '',
    confirmPassword: '',
  };
  const navigate = useNavigate();
  const { clearUserInfoAndToken } = useUserActions();
  const handleClick = async () => {
    const values = await form.validateFields();
    console.log('initFormValues', values);
    roleService
      .modifyPassword(values)
      .then(async (res) => {
        if (res > 0) {
          message.success('修改成功');
          setTimeout(() => {
            permissionService.Logout();
            clearUserInfoAndToken();
            navigate('/login');
          }, 2000);
        }
      })
      .catch(() => {
        message.error('修改失败');
      });
  };

  return (
    <Card className="!h-auto flex-col">
      <Form
        form={form}
        layout="vertical"
        initialValues={initFormValues}
        labelCol={{ span: 8 }}
        className="w-full"
      >
        <Form.Item<FieldType>
          label="旧密码"
          name="password"
          rules={[
            { required: true, message: '请输入旧密码' },
            { min: 6, message: '密码长度不能小于6位' },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item<FieldType>
          label="新密码"
          name="newPassword"
          rules={[
            PASSWORD_PATTERN, // 使用自定义验证规则
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') !== value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('新密码不能与旧密码相同'));
              },
            }),
          ]}
          extra="密码长度6-20位，必须包含大小写字母、数字和特殊字符中的任意三种"
        >
          <Input.Password />
        </Form.Item>

        <Form.Item<FieldType>
          label="请再次输入新密码"
          name="confirmPassword"
          dependencies={['newPassword']}
          rules={[
            { required: true, message: '请再次输入新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        >
          <Input.Password />
        </Form.Item>
      </Form>
      <div className="flex w-full justify-end">
        <Button type="primary" onClick={handleClick}>
          保存
        </Button>
      </div>
    </Card>
  );
}
